/**
 * 
 */
package cn.com.agameofthrones.AGoTLCGCards;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author li youhua
 * 
 */
public class AGoTCardsDB extends SQLiteOpenHelper {
	private static String DB_PATH = "/data/data/cn.com.agameofthrones.AGoTLCGCards/databases/";
	private static final String DB_NAME = "AGoTLCGCards.db";

	private SQLiteDatabase AGotCardsDataBase;

	private final Context AGoTContext;

	public AGoTCardsDB(Context context) {
		super(context, DB_NAME, null, 1);
		this.AGoTContext = context;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. 
	 * */
	private void initDataBase() throws IOException {

		// Open your local db as the input stream
		// InputStream myInput = AGoTContext.getAssets().open(DB_NAME);
		InputStream myInput = AGoTContext.getResources().openRawResource(
				R.raw.cards_db_init);
		InputStreamReader reader = new InputStreamReader(myInput);
		BufferedReader breader = new BufferedReader(reader);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME, str;

		// Open the empty db as the output stream
		FileWriter myOutput = new FileWriter(outFileName, true);

		while ((str = breader.readLine()) != null) {
			AGotCardsDataBase.execSQL(str);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
	 * .SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		AGotCardsDataBase = db;

			try {
				this.initDataBase();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
	@Override
	public void onOpen (SQLiteDatabase db){
		
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
	 * .SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}
}
